﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Collections;

/// <summary>
/// Summary description for Manager
/// </summary>
public class Manager
{
	public Manager()
	{
		//
		// TODO: Add constructor logic here
		//
	}

	public static DataTable PrepareLogEntriesforExport(DataTable logExport)
	{
		DataTable result = new DataTable();

		result.Columns.Add(new DataColumn("Date"));
		result.Columns.Add(new DataColumn("Teacher"));
		result.Columns.Add(new DataColumn("Type"));
		result.Columns.Add(new DataColumn("Note"));
		foreach (DataRow dr in logExport.Rows)
		{
			DataRow newdr = result.NewRow();
			newdr["Date"] = dr["LOG_DATE"];
			newdr["Teacher"] = dr["TEACHER_NAME"];
			newdr["Type"] = dr["LOG_TYPE"];
			newdr["Note"] = dr["ENTRY"];

			result.Rows.Add(newdr);
		}

		return result;
	}

	public static void ExportToCSV(DataTable table, HttpContext context, string reportName)
	{
	
		context.Response.Clear();

		foreach (DataColumn column in table.Columns)
		{
			context.Response.Write(column.ColumnName + ",");
		}

		context.Response.Write(Environment.NewLine);
		foreach (DataRowView dr in table.DefaultView)
		{
			DataRow row = dr.Row;
			for (int i = 0; i < table.Columns.Count; i++)
			{
				string text = row[i].ToString().Replace(",", string.Empty);
				if (row[i].GetType() == typeof(string))
				{
					text = "\"" + text + "\"";
				}
				context.Response.Write(text + ",");
			}

			context.Response.Write(Environment.NewLine);
		}

		context.Response.ContentType = "text/csv";
		context.Response.AppendHeader("Content-Disposition", string.Concat("attachment; filename=" ,reportName));
		context.Response.End();

	}

	public static List<TwoWeek> GetTwoWeeksForAdmin(DateTime selectedDate, DateTime start, DateTime end, out DateTime current)
	{
		current = DateTime.MinValue;
		start = start.AddDays(-(int)start.DayOfWeek);
		DateTime send = selectedDate.AddDays((double)(6 - selectedDate.DayOfWeek));
		int weeks = (int)((send - start).TotalDays / 7 - 1);
        //if (weeks < 0) weeks = 0;

		List<TwoWeek> result = new List<TwoWeek>();
		DateTime now = selectedDate;
		for (int i = 0; i <= weeks; i++)
		{
			//if (i > 2)
			//    break;
			TwoWeek week = new TwoWeek();
			week.Start = start;
			week.End = start.AddDays(13);

			if (week.End > end)
				week.End = end;

			result.Add(week);

			start = start.AddDays(7);

			if (((new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day)).Ticks >= week.Start.Ticks) && (now.Ticks <= week.End.Ticks))
			{
				current = week.Start;
			}
		}

		return result;
	}

	public static List<TwoWeek> GetTwoWeeks(DateTime selectedDate, DateTime start, DateTime end, out DateTime current)
	{
		List<TwoWeek> result = new List<TwoWeek>();
		TwoWeek week = new TwoWeek();
		week.Start = selectedDate.AddDays(-7 - (int)selectedDate.DayOfWeek);
		week.End = selectedDate.AddDays((double)(6 - selectedDate.DayOfWeek));

		if (week.Start < start)
			week.Start = start;
		if (week.End > end)
				week.End = end;
		result.Add(week);


		current = week.Start;
		//current = DateTime.MinValue;
		//start = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day).AddDays(-(int)start.DayOfWeek-2);
		//end = end.AddDays(+(int)start.DayOfWeek);
		//int weeks = (int)(end - start).TotalDays/14;

		//List<TwoWeek> result = new List<TwoWeek>();
		//DateTime now = selectedDate;
		//for (int i = 0; i <= weeks; i++)
		//{
		//    if (i > 2)
		//        break;
		//    TwoWeek week = new TwoWeek();
		//    week.Start = start;
		//    week.End = start.AddDays(13);

		//    if (week.End > end)
		//        week.End = end;

		//    result.Add(week);

		//    start = start.AddDays(14);

		//    if ((now.Ticks >= week.Start.Ticks) && (now.Ticks <= week.End.Ticks))
		//    {
		//        current = week.Start;
		//    }
		//}

		return result;
	}


	public static List<Week> GetWeeksForAdmin(DateTime selectedDate, DateTime start, DateTime end, out DateTime current)
	{
		current = DateTime.MinValue;
		start = start.AddDays(-(int)start.DayOfWeek);
		end = selectedDate.AddDays((double)(6 - selectedDate.DayOfWeek));
		int weeks = (int)(end - start).TotalDays / 7;

		List<Week> result = new List<Week>();
		DateTime now = selectedDate;
		for (int i = 0; i <= weeks; i++)
		{
			Week week = new Week();
			week.Start = start;
			week.End = start.AddDays(6);

			if (week.End > end)
				week.End = end;

			result.Add(week);

			start = start.AddDays(7);

			if ((now.Ticks >= week.Start.Ticks) && (now.Ticks <= week.End.Ticks))
			{
				current = week.Start;
			}
		}

		return result;
	}

	public static List<Week> GetWeeks(DateTime selectedDate, DateTime start, DateTime end, out DateTime current)
	{
		List<Week> result = new List<Week>();
		Week week = new Week();
		week.Start = selectedDate.AddDays(-(int)selectedDate.DayOfWeek);
		week.End = selectedDate.AddDays((double)( 6 -selectedDate.DayOfWeek));



		result.Add(week);
Week week1 = new Week();

		if ((week.Start - start).TotalDays > 7)
		{
			
			week1.Start = week.Start.AddDays(-7);
			week1.End = week.End.AddDays(-7);


			result.Add(week1);
		}

			if (week1.Start < start)
				week1.Start = start;
			if (week1.End > end)
				week1.End = end;

		if (week.Start < start)
			week.Start = start;
		if (week.End > end)
			week.End = end;

		current = week.Start;

		return result;
	}

	public static DataTable GetForExcel(decimal sectionId, DateTime start, DateTime end)
	{
		AttendanceEntry result = new AttendanceEntry();
		DataLayer dal = new DataLayer();
		string message = string.Empty;

		result.Students = dal.GetEnrolledStudents(PAConfiguration.ConnectionString, sectionId, out message);
		PALogManager.MessageLog(message);

		result.Records = dal.GetRecords(PAConfiguration.ConnectionString, sectionId, start, end, out message);
		PALogManager.MessageLog(message);

		DataTable dresult = new DataTable();

		DataColumn dcclastfirst = new DataColumn("Student Name");
		dcclastfirst.Caption = "Student Name";

		dresult.Columns.Add(dcclastfirst);

		DateTime temp = start;
		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = temp.ToString("ddd-d");
			dresult.Columns.Add(day);

			temp = temp.AddDays(1);

		}


		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = temp.ToString("ddd-d");
			dresult.Columns.Add(day);

			temp = temp.AddDays(1);

		}

		
		foreach (DataRow drstudent in result.Students.Rows)
		{
			DataRow dr = dresult.NewRow();
			decimal studentId = (decimal)drstudent["STUDENT_ID"];
			decimal enrollmentId = (decimal)drstudent["ENROLLMENT_ID"];
			dr[dcclastfirst] = drstudent["LASTFIRST"];
			dresult.Rows.Add(dr);
			temp = start;
			for (int i = 1; i <= 14; i++)
			{
				DataRow frow = Find(result.Records, studentId, enrollmentId, temp);
				temp = temp.AddDays(1);
				

				if (frow == null)
					continue;

				if (frow.IsNull("ATT_CODE"))
					continue;

				dr[i] = frow["ATT_CODE"];
			}
		}


		

		
		return dresult;
	}


	public static DataRow FindStudentRow(DataTable Records, string sectionname, DateTime day)
	{
		decimal dstudentId = 0;
		DateTime dday;
		foreach (DataRow dr in Records.Rows)
		{
			dstudentId = (decimal)dr["STUDENT_ID"];
			dday = (DateTime)dr["ATT_DATE"];

			if (string.Compare( sectionname, (string)dr["SECTION_NAME"], true)==0)
			
				if ((day.Year == dday.Year) && (day.Month == dday.Month) && (day.Day == dday.Day))
					return dr;
		}

		return null;
	}

	public static  DataRow Find(DataTable Records, decimal studentId, decimal enrollmentId, DateTime day)
	{
		decimal dstudentId = 0;
		decimal denrollmentId = 0;
		DateTime dday;
		foreach (DataRow dr in Records.Rows)
		{
			dstudentId = (decimal)dr["STUDENT_ID"];
			denrollmentId = (decimal)dr["ENROLLMENT_ID"];
			dday = (DateTime)dr["ATT_DATE"];

			if ((dstudentId == studentId)
				&& (denrollmentId == enrollmentId)
				&& ((day.Year == dday.Year) && (day.Month == dday.Month) && (day.Day == dday.Day)))
				return dr;
		}

		return null;
	}
	public static DataTable GetStudentEntryForExcel(
		decimal teacherId,
		decimal semesterId,
		decimal studentId,
		DateTime start,
		DateTime end)
	{
		AttendanceEntry result = new AttendanceEntry();
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		HashSet<string> table = new HashSet<string>();


		result.Students = dal.GetSections(PAConfiguration.ConnectionString, teacherId, semesterId, out message).Tables[0];
		PALogManager.MessageLog(message);

		result.Records = dal.GetStudentAlRecords(PAConfiguration.ConnectionString, studentId, start, end, out message);
		PALogManager.MessageLog(message);

		Hashtable sections = new Hashtable();
		foreach (DataRow dr in result.Records.Rows)
		{
			sections[(string)dr["SECTION_NAME"]] = true;
		}

		DataTable newsections = result.Students.Clone();

		int index = 1;
		foreach (string key in sections.Keys)
		{
			DataRow dr = newsections.NewRow();
			dr["SECTION_ID"] = index;
			dr["SECTION_TITLE"] = key;
			index++;
			newsections.Rows.Add(dr);
		}

		result.Students = newsections;

		DataTable dresult = new DataTable();


		DataColumn dcclastfirst = new DataColumn("Section Name");
		dcclastfirst.Caption = "Section Name";
		dresult.Columns.Add(dcclastfirst);
		DateTime temp = start;
		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = temp.ToString("ddd-d");
			dresult.Columns.Add(day);

			temp = temp.AddDays(1);

		}


		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = temp.ToString("ddd-d");
			dresult.Columns.Add(day);

			temp = temp.AddDays(1);

		}

		

		foreach (DataRow drstudent in result.Students.Rows)
		{
			DataRow dr = dresult.NewRow();
			string sectionname = (string)drstudent["SECTION_TITLE"];
			dr[dcclastfirst] = drstudent["SECTION_TITLE"];
			dresult.Rows.Add(dr);
			temp = start;
			for (int i = 1; i <= 14; i++)
			{
				DataRow frow = FindStudentRow(result.Records, sectionname, temp);
				temp = temp.AddDays(1);


				if (frow == null)
					continue;

				if (frow.IsNull("ATT_CODE"))
					continue;

				dr[i] = frow["ATT_CODE"];
			}
		}
		dresult.DefaultView.Sort = "[Section Name] ASC";
		return dresult;
	}


	public static AttendanceEntry GetStudentEntry(
		decimal teacherId,
		decimal semesterId,
		decimal studentId, 
		DateTime start, 
		DateTime end)
	{
		AttendanceEntry result = new AttendanceEntry();
		DataLayer dal = new DataLayer();
		string message = string.Empty;
		HashSet<string> table = new HashSet<string>();


		result.Students = dal.GetSectionsShort(PAConfiguration.ConnectionString, teacherId, semesterId, out message).Tables[0];
		PALogManager.MessageLog(message);

		result.Records = dal.GetStudentAlRecords(PAConfiguration.ConnectionString, studentId, start, end, out message);
		PALogManager.MessageLog(message);

	 

		Hashtable sections = new Hashtable();
        DataTable newsections = result.Students.Clone(); //Sections

        DataColumn cEID = new DataColumn("ENROLLMENT_ID");
        cEID.DataType = typeof(decimal);
        newsections.Columns.Add(cEID);

		foreach (DataRow dr in result.Records.Rows)
		{
			//sections[(string)dr["SECTION_NAME"]] = dr["ENROLLMENT_ID"];

            if(!sections.ContainsKey(dr["SECTION_ID"]))
            {
                sections[dr["SECTION_ID"]] = dr["ENROLLMENT_ID"];
                DataRow drN = newsections.NewRow();
                drN["SECTION_ID"] = dr["SECTION_ID"];
                drN["SECTION_TITLE"] = dr["SECTION_NAME"];
                drN["ENROLLMENT_ID"] =dr["ENROLLMENT_ID"];
                newsections.Rows.Add(drN);
            }
		}
	
        //DataTable newsections = result.Students.Clone(); //Sections

		//decimal index ;
		//foreach (decimal key in sections.Keys)
		//{
            //index = decimal.MaxValue; 
            //DataRow dr = newsections.NewRow();
            //foreach (DataRow sdr in result.Students.Rows)
            //{
            //    if (string.Compare(key, (string)sdr["SECTION_TITLE"], true) == 0)
            //    {
            //        index = (decimal)sdr["SECTION_ID"];
            //        break;
            //    }
            //}
            //dr["SECTION_ID"] = index;
            //dr["SECTION_TITLE"] = key;

            //dr["SECTION_ID"] = key;
            //dr["SECTION_TITLE"] = ((DataRow)sections[key])["SECTION_NAME"];
            //dr["ENROLLMENT_ID"] = ((DataRow)sections[key])["SECTION_NAME"]; //Student's enrollment id in the section

			//newsections.Rows.Add(dr);
		//}

		result.Students = newsections;

		DataTable dresult = new DataTable();

		DataColumn dcstudentId = new DataColumn("STUDENT_ID");
		dcstudentId.Caption = "Section Name";
		dcstudentId.DataType = typeof(decimal);
		DataColumn dcenrollmentId = new DataColumn("ENROLLMENT_ID");
		dcenrollmentId.DataType = typeof(decimal);
		DataColumn dcclastfirst = new DataColumn("LASTFIRST");
		dresult.Columns.Add(dcstudentId);
		dresult.Columns.Add(dcenrollmentId);
		dresult.Columns.Add(dcclastfirst);

		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = start.ToString("ddd-d");
			dresult.Columns.Add(day);

			start = start.AddDays(1);

		}

		dresult.Columns.Add(new DataColumn("EditButtonWeek1"));

		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = start.ToString("ddd-d");
			dresult.Columns.Add(day);

			start = start.AddDays(1);

		}

		dresult.Columns.Add(new DataColumn("EditButtonWeek2"));

		foreach (DataRow drstudent in result.Students.Rows)
		{
			DataRow dr = dresult.NewRow();

            //decimal enrollmentId = 0;

            //foreach (DataRow drl in result.Records.Rows)
            //{
            //    if (string.Compare((string)drl["SECTION_NAME"], (string)drstudent["SECTION_TITLE"], true) == 0)
            //    {
            //        enrollmentId = (decimal)drl["ENROLLMENT_ID"];
            //        break;
            //    }
            //}

			dr[dcstudentId] = drstudent["SECTION_ID"];
			dr[dcclastfirst] = drstudent["SECTION_TITLE"];
            dr[dcenrollmentId] = drstudent["ENROLLMENT_ID"]; //sections[(string)drstudent["SECTION_TITLE"]];
			dresult.Rows.Add(dr);
		}


		result.Result = dresult;
		result.Result.DefaultView.Sort = "LASTFIRST ASC";
		return result;
	}
	public static AttendanceEntry GetEntry(decimal sectionId, DateTime start, DateTime end)
	{
		AttendanceEntry result = new AttendanceEntry();
		DataLayer dal = new DataLayer();
		string message = string.Empty;

		result.Students = dal.GetEnrolledStudents(PAConfiguration.ConnectionString, sectionId, out message);
		PALogManager.MessageLog(message);

		result.Records = dal.GetRecords(PAConfiguration.ConnectionString, sectionId, start, end, out message);
		PALogManager.MessageLog(message);

		DataTable dresult = new DataTable();

		DataColumn dcstudentId = new DataColumn("STUDENT_ID");
		dcstudentId.Caption = "Student Name";
		dcstudentId.DataType = typeof(decimal);
		DataColumn dcenrollmentId = new DataColumn("ENROLLMENT_ID");
		dcenrollmentId.DataType = typeof(decimal);
		DataColumn dcclastfirst = new DataColumn("LASTFIRST");
		dresult.Columns.Add(dcstudentId);
		dresult.Columns.Add(dcenrollmentId);
		dresult.Columns.Add(dcclastfirst);

		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = start.ToString("ddd-d");
			dresult.Columns.Add(day);

			start = start.AddDays(1);

		}

		dresult.Columns.Add(new DataColumn("EditButtonWeek1"));

		for (int i = 0; i < 7; i++)
		{
			DataColumn day = new DataColumn();
			day.ColumnName = start.ToString("ddd-d");
			dresult.Columns.Add(day);

			start = start.AddDays(1);

		}

		dresult.Columns.Add(new DataColumn("EditButtonWeek2"));

		foreach(DataRow drstudent in result.Students.Rows)
		{
			DataRow dr = dresult.NewRow();

			dr[dcstudentId] = drstudent["STUDENT_ID"];
			dr[dcclastfirst] = drstudent["LASTFIRST"];
			dr[dcenrollmentId] = drstudent["ENROLLMENT_ID"];
			dresult.Rows.Add(dr);
		}


		result.Result = dresult;
		return result;
	}
}
